package com.warrior.bluetooth;

import com.warrior.main.MyLog;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class WaitToCallBack implements Runnable{

	private boolean isMessageArrived = false;
	private IFinishTime iFinishTime;
	private Handler handler;
	private String myMessage;
	private final static String MESSAGE_KEY = "key";
	
	public WaitToCallBack(){
		buildHandler();
	}
	private void buildHandler(){
		 handler = new Handler(){
	        public void handleMessage(Message message) {
	        	String str = message.getData().getString(MESSAGE_KEY);
	        	if(str == null){
	        		//Log.d(MyLog.WAIT_TO_CALL_BACK,"message is null in UI thread");
	        		str = "null";
	        	}
	        	Log.d(MyLog.WAIT_TO_CALL_BACK,"message arrived to UI thread message = " + str);
	        	iFinishTime.finishTime(str);
	        }
	    };
	}
	
	public boolean isMessageArrive() {
		return isMessageArrived;
	}
	public void setFinishTimeListener(IFinishTime iMessageArrived) {
		this.iFinishTime = iMessageArrived;
	}
	public void setMessageArrived(){
		isMessageArrived = true;
	}
	public void setMessage(String msg){
		myMessage = msg;
	}
	@Override
	public void run() {
		//try{
			isMessageArrived = false;
			Sync.waitTime(250);
			if(!isMessageArrived){
				Message msg = handler.obtainMessage();
			 	Bundle bundle = new Bundle();
		        bundle.putString(MESSAGE_KEY, myMessage);
		        msg.setData(bundle);
		        Log.d(MyLog.WAIT_TO_CALL_BACK,"before send message to UI thread message = " + myMessage);
		        if(myMessage == null){
		        	Log.d(MyLog.WAIT_TO_CALL_BACK,"before send message to UI thread message is null");
		        }
				handler.sendMessage(msg);
			}
//		} 
//		catch (InterruptedException e) {
//	        // good practice
//	        Thread.currentThread().interrupt();
//		}
	}
	public interface IFinishTime{
		void finishTime(String msg);
	}
}
